package com.ml.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Splitter;
import com.ml.gateway.utils.JwtUtil;
import com.ml.gateway.utils.ResponseEnum;
import com.ml.gateway.utils.ReturnResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author ml
 * @date 2023/3/2 17:11
 */

@Slf4j
@Order(1)
@Component
@WebFilter(filterName = "MyFilter", urlPatterns = {"/**"})
public class MyFilter implements Filter {
    @Resource
    private JwtUtil jwtUtils;
    /**
     *  获取配置文件中不需要过滤的url
      */
    @Value("${filter.config.excludeUrls}")
    private String excludeUrls;

    private List<String> excludes;


    @Override
    public void init(FilterConfig filterConfig) {
        // 移除配置文件中不过滤uri，字符串的前空白和尾部空白
        excludes = Splitter.on(",").trimResults().splitToList(this.excludeUrls);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setCharacterEncoding("utf-8");
        //获取请求uri
        String uri = request.getRequestURI();
        // 获取头中token
        String token = request.getHeader("token");
        try {
            // 判断请求uri是否需要过滤（方法在下面）
            if (this.isExcludesUrl(uri)) {
                // 不需要，放行
                chain.doFilter(req, resp);
            } else {
                // 验证头中的token（方法在下面）
                if (!jwtUtils.verifyToken(token)) {
                    // 验证失败，返回验证失败消息
                    response.getWriter().write(JSON.toJSONString(ReturnResponse.failure(ResponseEnum.VALID_ERROR)));
                    return;
                }

                // 验证成功，放行
                chain.doFilter(request, resp);
            }
        } catch (Exception e) {
            log.error("过滤器异常", e);
            // 抛出异常，返回验证失败消息
            response.getWriter().write(JSON.toJSONString(ReturnResponse.failure(ResponseEnum.VALID_ERROR)));
        } finally {
            // 将缓冲信息输出到页面
            response.flushBuffer();
        }

    }

    @Override
    public void destroy() {

    }


    private boolean isExcludesUrl(String path) {
        for (String v : this.excludes) {

            // 判断请求uri 是否满足配置文件uri要求
            if (path.startsWith(v)) {
                // 满足、也就是请求uri 为 登录、注册，返回true
                return true;
            }
        }
        // 不满足、也就是请求uri 不是登录、注册，返回false
        return false;
    }
}

